package com.leicx.guli.search.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.base.Splitter;
import com.leicx.guli.common.enums.GuliExceptionEnum;
import com.leicx.guli.common.exception.RRException;
import com.leicx.guli.common.to.es.SkuEsModel;
import com.leicx.guli.common.utils.FeignUtil;
import com.leicx.guli.common.utils.JsonUtil;
import com.leicx.guli.common.utils.R;
import com.leicx.guli.search.config.EsConfig;
import com.leicx.guli.search.constant.EsConstant;
import com.leicx.guli.search.feign.ProductFeignService;
import com.leicx.guli.search.service.MallSearchService;
import com.leicx.guli.search.vo.AttrResponseVo;
import com.leicx.guli.search.vo.SearchParam;
import com.leicx.guli.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author daxiong
 * @date 2022/5/18 下午10:17
 */
@Service
@Slf4j
public class MallSearchServiceImpl implements MallSearchService {

    @Resource
    RestHighLevelClient client;
    @Resource
    ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam searchParam) {
        // 构造查询请求对象
        SearchRequest searchRequest = buildQueryRequest(searchParam);

        // 执行检索
        SearchResponse response;
        try {
            response = client.search(searchRequest, EsConfig.COMMON_OPTIONS);
        } catch (IOException exception) {
            log.error("es查询错误：{}", exception.getMessage());
            throw new RRException(GuliExceptionEnum.ES_QUERY_ERROR);
        }
        // 构造查询返回对象
        return buildQueryResponse(response, searchParam);
    }

    /**
     * 构造查询请求对象
     *
     * @param searchParam 搜索对象
     * @return org.elasticsearch.action.search.SearchRequest
     * @author daxiong
     * @date 2022/5/24 下午9:41
     */
    private SearchRequest buildQueryRequest(SearchParam searchParam) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 构造检索条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // ---------- 查询，过滤 --------------
        // 1、skuTitle模糊查询
        if (StrUtil.isNotEmpty(searchParam.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        }
        // 2.1、分类id查询
        if (Objects.nonNull(searchParam.getCatalog3Id())) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
        }
        // 2.2、品牌id查询
        if (CollUtil.isNotEmpty(searchParam.getBrandId())) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }
        // 2.3、属性字段查询
        if (CollUtil.isNotEmpty(searchParam.getAttrs())) {
            for (String attr : searchParam.getAttrs()) {
                // 每一个属性都得生成一个nested查询
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                // &attrs=1_5寸:8寸&attrs=2_16G:8G
                List<String> list = Splitter.on("_").omitEmptyStrings().splitToList(attr);
                String attrId = list.get(0);
                List<String> attrValueList = Splitter.on(":").omitEmptyStrings().splitToList(list.get(1));
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValueList));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        // 2.4、是否有库存查询
        if (Objects.nonNull(searchParam.getHasStock())) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", Objects.equals(searchParam.getHasStock(), 1)));
        }
        // 2.5、价格区间查询
        if (StrUtil.isNotEmpty(searchParam.getSkuPrice())) {
            List<String> list = Splitter.on("_").omitEmptyStrings().splitToList(searchParam.getSkuPrice());
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            if (list.size() == 2) {
                rangeQuery.gte(list.get(0)).lte(list.get(1));
            } else if (list.size() == 1) {
                if (searchParam.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(list.get(0));
                } else if (searchParam.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(list.get(0));
                }
            }
            boolQuery.filter(rangeQuery);
        }
        sourceBuilder.query(boolQuery);

        // ---------- 排序，分页，高亮 --------------
        if (StrUtil.isNotEmpty(searchParam.getSort())) {
            // 排序，sort=saleCount_asc/desc
            List<String> sortList = Splitter.on("_").omitEmptyStrings().splitToList(searchParam.getSort());
            String sortMode = sortList.get(1);
            SortOrder sortOrder = sortMode.equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(sortList.get(0), sortOrder);
        }
        // 分页
        Integer pageNum = searchParam.getPageNum();
        int from = (pageNum - 1) * EsConstant.PAGE_SIZE;
        sourceBuilder.from(from);
        sourceBuilder.size(EsConstant.PAGE_SIZE);
        // 高亮
        if (StrUtil.isNotEmpty(searchParam.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }

        // ---------- 聚合分析 --------------
        // 品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brandAgg);
        // 分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalogAgg);
        // 属性聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attrAgg.subAggregation(attrIdAgg);
        sourceBuilder.aggregation(attrAgg);

        String s = sourceBuilder.toString();
        System.out.println("构建的DSL为：" + s);

        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
    }

    /**
     * 构造查询返回对象
     *
     * @param response
     * @param searchParam
     * @return com.leicx.guli.search.vo.SearchResult
     * @author daxiong
     * @date 2022/5/24 下午9:42
     */
    private SearchResult buildQueryResponse(SearchResponse response, SearchParam searchParam) {
        SearchResult searchResult = new SearchResult();
        SearchHits hits = response.getHits();
        long total = hits.getTotalHits().value;

        List<SkuEsModel> esModels = new ArrayList<>();
        for (SearchHit hit : hits.getHits()) {
            String sourceAsString = hit.getSourceAsString();
            SkuEsModel esModel = JsonUtil.parseObject(sourceAsString, SkuEsModel.class);
            // 设置高亮信息
            if (StrUtil.isNotEmpty(searchParam.getKeyword())) {
                String skuTitle = hit.getHighlightFields().get("skuTitle").getFragments()[0].string();
                esModel.setSkuTitle(skuTitle);
            }
            esModels.add(esModel);
        }
        // 设置产品信息
        searchResult.setProducts(esModels);

        // 设置品牌
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        List<SearchResult.BrandVo> brandVoList = new ArrayList<>();
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            long brandId = bucket.getKeyAsNumber().longValue();
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandNameAgg.getBuckets().get(0).getKeyAsString());
            brandVo.setBrandImg(brandImgAgg.getBuckets().get(0).getKeyAsString());
            brandVoList.add(brandVo);
        }
        searchResult.setBrands(brandVoList);
        // 设置属性
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        List<SearchResult.AttrVo> attrVoList = new ArrayList<>();
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            long attrId = bucket.getKeyAsNumber().longValue();
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrNameAgg.getBuckets().get(0).getKeyAsString());
            attrVo.setAttrValue(attrValueAgg.getBuckets().stream()
                    .map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList()));
            attrVoList.add(attrVo);
        }
        searchResult.setAttrs(attrVoList);

        // 设置分类
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVoList = new ArrayList<>();
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            long catalogId = bucket.getKeyAsNumber().longValue();
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            catalogVo.setCatalogId(catalogId);
            catalogVo.setCatalogName(catalogNameAgg.getBuckets().get(0).getKeyAsString());
            catalogVoList.add(catalogVo);
        }
        searchResult.setCatalogs(catalogVoList);

        searchResult.setPageNum(searchParam.getPageNum());
        searchResult.setTotal(total);
        int totalPages = (int) (total % EsConstant.PAGE_SIZE == 0 ? total / EsConstant.PAGE_SIZE : total / EsConstant.PAGE_SIZE + 1);
        searchResult.setTotalPages(totalPages);

        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);

        //6、构建面包屑导航
        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0) {
            List<SearchResult.NavVo> collect = searchParam.getAttrs().stream().map(attr -> {
                //1、分析每一个attrs传过来的参数值
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                if (r.success()) {
                    AttrResponseVo data = FeignUtil.formatClass(r, "attr", AttrResponseVo.class);
                    navVo.setNavName(data.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }

                //2、取消了这个面包屑以后，我们要跳转到哪个地方，将请求的地址url里面的当前置空
                //拿到所有的查询条件，去掉当前
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr, "UTF-8");
                    encode.replace("+", "%20");  //浏览器对空格的编码和Java不一样，差异化处理
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace = searchParam.get_queryString().replace("&attrs=" + encode, "");
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);

                return navVo;
            }).collect(Collectors.toList());
            searchResult.setNavs(collect);
        }
        return searchResult;
    }

}
